// with polyfills
import 'core-js/stable'
import 'regenerator-runtime/runtime'

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store/'
import i18n from './locales'
import { VueAxios } from './utils/request'
import ProLayout, { PageHeaderWrapper } from '@ant-design-vue/pro-layout'
import themePluginConfig from '../config/themePluginConfig'
import PageBreadcrumb from '@/components/PageBreadcrumb/PageBreadcrumb'
import {
  Table,
  TableColumn,
  Loading,
  Cascader,
  Tree,
  Select,
  InputNumber,
  Input,
  Image
} from 'element-ui';
Vue.use(Table);
Vue.use(TableColumn);
Vue.use(Loading.directive);
Vue.use(Cascader);
Vue.use(Tree);
Vue.use(Select);
Vue.use(InputNumber);
Vue.use(Input);
Vue.use(Image);
// mock
// WARNING: `mockjs` NOT SUPPORT `IE` PLEASE DO NOT USE IN `production` ENV.
//取消mock，使用服务器真实的数据
// import './mock'

import bootstrap from './core/bootstrap'
import './core/lazy_use'
import './permission' // permission control
import './utils/filter' // global filter
import './global.less'

import { getDicts } from "@/api/system/dict/data";
import { getConfigKey } from "@/api/system/param";
import { parseTime, resetForm, addDateRange, selectDictLabel, selectDictLabels, handleTree } from "@/utils/iwmake";

// 引入vue-UUID组件
import UUID from 'vue-uuid'
import VueUeditorWrap from 'vue-ueditor-wrap' // ES6 Module
// 或者在 main.js 里将它注册为全局组件


import axios from 'axios'

import VueClipboard  from 'vue-clipboard2'

//时间格式化
import myTimerFormnat from './utils/myTimeFormat'
import JsonExcel from 'vue-json-excel'
import 'element-ui/lib/theme-chalk/index.css';
Vue.component('downloadExcel', JsonExcel)
Vue.use( VueClipboard )

Vue.prototype.$loading = Loading.service;
axios.defaults.baseURL='#'
Vue.prototype.$http = axios
//笛卡尔积
//计算属性-属性值对应的SKU组合
import cartesianProduct4SpecSpecValueSku from './utils/cartesianProduct'
Vue.prototype.$cartesianProduct4SpecSpecValueSku=cartesianProduct4SpecSpecValueSku;

Vue.component('vue-ueditor-wrap', VueUeditorWrap)
// 全局方法挂载
Vue.prototype.getDicts = getDicts
Vue.prototype.getConfigKey = getConfigKey
Vue.prototype.parseTime = parseTime
Vue.prototype.resetForm = resetForm
Vue.prototype.addDateRange = addDateRange
Vue.prototype.selectDictLabel = selectDictLabel
Vue.prototype.selectDictLabels = selectDictLabels
Vue.prototype.handleTree = handleTree

Vue.config.productionTip = false
//uuid
Vue.use(UUID)

// mount axios to `Vue.$http` and `this.$http`
Vue.use(VueAxios)
Vue.component('pro-layout', ProLayout)
Vue.component('page-header-wrapper', PageHeaderWrapper)
Vue.component('page-breadcrumb', PageBreadcrumb)

window.umi_plugin_ant_themeVar = themePluginConfig.theme

// 导入极验
require('@/assets/js/gt.js');
// 绑定到原型
Vue.prototype.$initGeet=initGeetest;


//过滤器
Vue.filter('sysTimerFormnat', function (value) {
  if (!value) return '无数据'
  return myTimerFormnat(value)
})
HTMLElement.prototype.REMOVE_SELF_FUNC = function(){
    if(this.parentNode){
        this.parentNode.removeChild(this);
    }
}
//使用Vue.mixin的方法拦截了路由事件、keep-alive事件
window.current_component_globle_remove = false
window.current_component_globle_remove_list = []
window.current_component_globle_remove_step_2_2 = null
window.current_component_globle_level_params_route = null
window.current_component_globle_component_instace = null
Vue.mixin({
  deactivated(){
    // console.log('deactivated',this.$route.path,this.$options.name)
  },
  activated(){

    if(this.$route && this.$route.params && JSON.stringify(this.$route.params) !="{}"
      && window.current_component_globle_level_params_route == this.$route.path
      && this.$vnode
      && this.$vnode.data.keepAlive){
      // console.log("activated进入后" , this.$route.path,this.$route.params)
      // console.log('activated params path name',this.$route.params,this.$route.path,this.$options.name)
      let on = this.$options.name
      let tempKp = this.$store.state.app.keepAliveListExcludeNames
      if(tempKp && tempKp.length > 0){
        tempKp = tempKp.split(",")
        let kpf = tempKp.find((item)=>{
          return item == on
        })
        //还没有加入keepAliveListExcludeNames
        if(!kpf){
          tempKp.push(on)
          this.$store.commit('setKeepAliveListExcludeNames',tempKp.join())
        }
      }else{
          this.$store.commit('setKeepAliveListExcludeNames',[on].join())
      }
    }
    //当前的组件实例
    if(this.$route
      && window.current_component_globle_level_params_route == this.$route.path
      && this.$vnode
      && this.$vnode.data.keepAlive
	  && 'RouteView' != this.$options.name){
       console.log('===activated component===',this.$options.name,this.$route.path)
      window.current_component_globle_component_instace = this

      //刷新按钮
      //先删除之前的刷新按钮
      let allGcftr = document.querySelectorAll(".globle_css_for_tab_refresh")
      // console.log(allGcftr)
      if(allGcftr){
        allGcftr.forEach((item)=>{
            item.REMOVE_SELF_FUNC()
        })
      }
      let iElement = document.createElement('img');
      iElement.setAttribute('class','globle_css_for_tab_refresh')
      iElement.setAttribute('src','https://91beeshare.com:443/user//springUpload/img/20220218104559.png')
      iElement.setAttribute('style','margin-left:10px;')
      document.querySelector(".ant-tabs-tab-active").children[0].appendChild(iElement)
      iElement.addEventListener('click', () => {
            let deg = 360;
            iElement.style = 'margin-left:10px;transition: .5s ease; '
            iElement.style.transform = `rotate(${deg}deg)`;
            deg += 360;    
            setTimeout(function () {
            iElement.style = 'margin-left:10px;transform: rotate(0deg); transition: 0s ease; '
            }, 1000);
         //console.log('刷新按钮')
        if(window.current_component_globle_component_instace
          && window.current_component_globle_component_instace.__GLOBLE_REFRESH_FUNC__){
          window.current_component_globle_component_instace.__GLOBLE_REFRESH_FUNC__()
        }
      })
    }
    // console.log('activated',this.$route.path,this.$options.name)
    if (!window.current_component_globle_remove){
      let findName_ = window.current_component_globle_remove_list.find((item)=>{
        return item == this.$route.path
      })

      if(findName_){

        // console.log('activated ',findName_,this.$options.name)
        if (this.$vnode && this.$vnode.data.keepAlive){
          // console.log('activated keepAlive',this.$route.path,this.$options.name)

          // 重置不是当前页面关闭
          window.current_component_globle_remove = false
          window.current_component_globle_remove_list =
          window.current_component_globle_remove_list.filter((item)=>{
              return item != this.$route.path
          });

          if (this.$vnode.parent && this.$vnode.parent.componentInstance && this.$vnode.parent.componentInstance.cache)
          {
            if (this.$vnode.componentOptions)
            {
              var key = this.$vnode.key == null
                ? this.$vnode.componentOptions.Ctor.cid + (this.$vnode.componentOptions.tag ? `::${this.$vnode.componentOptions.tag}` : '')
                : this.$vnode.key;
              var cache = this.$vnode.parent.componentInstance.cache;
              var keys  = this.$vnode.parent.componentInstance.keys;
              console.log('activated keepAlive key',key)
              console.log('activated keepAlive cache',cache)
              console.log('activated keepAlive keys',keys)
              if (cache[key])
              {
                if (keys.length) {
                  var index = keys.indexOf(key);
                  if (index > -1) {
                    keys.splice(index, 1);
                  }
                }
                delete cache[key];
              }
            }
          }
          //删除
          this.$destroy();

          console.log("step:2-2")
          //再一次进入
          // 怎么关闭当前multitale页面？？
          // --①先往回跳转
          if(window.current_component_globle_remove_step_2_2){
            //--②再跳转回来
            let temp = window.current_component_globle_remove_step_2_2
            window.current_component_globle_remove_step_2_2 = this.$route.path
            this.$router.push({path:temp})
          }
        }
      }
      else{
        //--③再跳转回来
        if(window.current_component_globle_remove_step_2_2){
          let temp_ = window.current_component_globle_remove_step_2_2
          window.current_component_globle_remove_step_2_2 = null
          this.$router.push({path:temp_})
        }
      }
    }
  },
  beforeRouteUpdate:function(to, from, next){
    //当前页面关闭
    if (!window.current_component_globle_remove){
      // console.log("beforeRouteUpdate进入后" , this.$route.path,this.$route.params)
      // console.log('beforeRouteUpdate to',to.name,this,this.$options.name)
      let findName_ = window.current_component_globle_remove_list.find((item)=>{
        return item == to.path
      })
      // //被当前页面关闭过，现在要打开关闭的页面
      if(findName_){
        //清除keep-alive和组件，重新初始化
        console.log("step:2")
        //转：activated
        window.current_component_globle_remove_step_2_2 = from.name
      }
      // //没有被当前页面关闭过，当前页面跳转
      else{
        //TODO
        console.log("step:3")
      }
      next();
    }
  },
  beforeRouteLeave:function(to, from, next){
    if(window.current_component_globle_remove){
      // console.log('beforeRouteLeave from',from.name)
      let findName = window.current_component_globle_remove_list.find((item)=>{
        return item == from.path
      })
      //from就是关闭的页面
      if(findName){
        //删除关闭页面的keep-alive
        if (this.$vnode && this.$vnode.data.keepAlive)
        {
          if (this.$vnode.parent && this.$vnode.parent.componentInstance && this.$vnode.parent.componentInstance.cache)
          {
            if (this.$vnode.componentOptions)
            {
              var key = this.$vnode.key == null
                ? this.$vnode.componentOptions.Ctor.cid + (this.$vnode.componentOptions.tag ? `::${this.$vnode.componentOptions.tag}` : '')
                : this.$vnode.key;
              var cache = this.$vnode.parent.componentInstance.cache;
              var keys  = this.$vnode.parent.componentInstance.keys;
              if (cache[key])
              {
                if (keys.length) {
                  var index = keys.indexOf(key);
                  if (index > -1) {
                    keys.splice(index, 1);
                  }
                }
                delete cache[key];
              }
            }
          }
        }
        //删除关闭页面
        this.$destroy();
        //重置不是当前页面关闭
        window.current_component_globle_remove = false
        window.current_component_globle_remove_list =
          window.current_component_globle_remove_list.filter((item)=>{
            return item != from.path
          });
        console.log("step:1")
      }else{
        window.current_component_globle_remove = false
        console.log("step:1-no")
      }
    }
    next();
  }
});
new Vue({
  router,
  store,
  i18n,
  created: bootstrap,
  render: h => h(App)
}).$mount('#app')
